<script setup>
import { ref, onMounted, reactive } from 'vue';
import SingleUpload from '@/components/upload/singleUpload.vue';
import { Delete, EditPen, Plus } from '@element-plus/icons-vue'
import { getCategoryListApi, saveCategoryInfoApi, getCategoryInfoApi, updateCategoryInfoApi, deleteCategoryApi } from '@/apis/pms/category.js'


// 图标分组
const uploadType = "category";
// 树的数据配置
const defaultProps = {
  label: 'name',
  children: 'children',
}

const loading = ref(false)

// 默认展示节点
const expandedKey = ref([]);
// 获取分类数据
const categoryData = ref([])
const getCategoryList = async () => {
  loading.value = true
  const res = await getCategoryListApi();
  categoryData.value = res.data;
  loading.value = false
}
// 数据表单
const categoryForm = ref({
  id: '',
  name: '',
  pid: '',
  level: '',
  visible: 0,
  sort: '',
  icon: null,
})
// 对话框隐藏/显示
const dialogFormVisible = ref(false)
let title = '';

// 添加一级分类
const addCategoryOne = () => {
  title = '添加';
  // 初始化数据
  categoryForm.value.pid = 0;
  categoryForm.value.level = 1;
  dialogFormVisible.value = true;
}

// 添加子分类
const append = (data) => {
  // 初始化数据
  title = '添加';
  categoryForm.value.pid = data.id;
  categoryForm.value.level = data.level + 1;
  expandedKey.value = []
  expandedKey.value.push(categoryForm.value.pid)
  dialogFormVisible.value = true;
}

// 编辑分类
const edit = async (data) => {
  // 获取回显数据
  title = '修改';
  const res = await getCategoryInfoApi(data.id);
  console.log(res.data)
  categoryForm.value = res.data;
  // 设置默认展开节点
  expandedKey.value = []
  if(categoryForm.value.pid === 0){
    expandedKey.value.push(categoryForm.value.id)
  }else{
    expandedKey.value.push(categoryForm.value.pid)
  }
  dialogFormVisible.value = true;
}

// 删除单个分类
const remove = (data) => {
  ElMessageBox.confirm(
    '你确定要删除此分类吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      var id = []
      id.push(data.id)
      // 删除分类
      deleteCategoryApi(id)
        .then(res => {
          if (res.code === 0) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            // 重新获取数据
            getCategoryList();
            // 默认展开节点
            expandedKey.value = [];
            expandedKey.value.push(data.pid);
          }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 批量删除
let ids = []
const deleteCategorys = () => {
  if (ids.length === 0) {
    ElMessage({
      type: 'info',
      message: '未选择数据',
    })
    return;
  }
  ElMessageBox.confirm(
    '你确定要删除此分类吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      // 删除分类
      deleteCategoryApi(ids)
        .then(res => {
          if (res.code === 0) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            // 重新获取数据
            getCategoryList();
            ids = []
          }
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 点击确定
const handlerConfirm = () => {
  // 没有id是添加
  if (categoryForm.value.id === '' || categoryForm.value.id === null || categoryForm.value.id === void 0) {
    saveCategoryInfoApi(categoryForm.value)
      .then(res => {
        if (res.code === 0) {
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          // 重新获取数据
          getCategoryList()
          // 重置数据
          categoryForm.value = {};
          categoryForm.value.visible = 0;
          dialogFormVisible.value = false;
        }
      })
  } else {
    // 有id是修改分类数据
    updateCategoryInfoApi(categoryForm.value)
      .then(res => {
        if (res.code === 0) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          // 重新获取数据
          getCategoryList();
          // 重置数据
          categoryForm.value = {};
          categoryForm.value.visible = 0;
          dialogFormVisible.value = false;
        }
      })
  }
}

// 点击取消
const singleUploadComponent = ref();
const hadnlerCancel = () => {
  if (categoryForm.value.id === null || categoryForm.value.id === '' || categoryForm.value.id === void 0) {
    if (categoryForm.value.icon === null || categoryForm.value.icon === '' || categoryForm.value.icon === void 0) {
      dialogFormVisible.value = false;
    } else {
      // id为空,添加时点击取消，删除上传的图片
      singleUploadComponent.value.handleRemove();
      dialogFormVisible.value = false;
    }
  } else {
    // 修改点击取消，不能删除
    categoryForm.value = {};
    categoryForm.value.visible = 0;
    dialogFormVisible.value = false;
  }
}

// 点击复选框
const handleCheckChange = (data, checkData) => {
  //console.log(expandedKey.value)
  ids = checkData.checkedNodes.filter(el => el.children.length === 0).map(obj => obj.id)
  // ids = checkData.checkedKeys;
}

// 排序字段校验
const checkSort = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入排序字段"))
  } else if (value < 0) {
    callback(new Error("排序字段必须是一个大于等于0的数"))
  } else {
    callback()
  }
}


// 数据校验
const rules = reactive({
  name: [{ requied: true, message: '请输入分类名', trigger: 'blur' }],
  sort: [{ requied: true, validator: checkSort, trigger: 'blur' }]
})

onMounted(() => getCategoryList())
</script>

<template>
  <div class="container" v-loading="loading">
    <el-row>
      <el-col :span="24" style="display: flex;justify-content: flex-start;align-items: center;margin-bottom: 10px;">
        <el-button type="primary" plain @click="addCategoryOne">添加一级分类</el-button>
        <el-button type="danger" plain @click="deleteCategorys">批量删除</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <!-- 树结构 -->
        <el-tree :highlight-current="true" :data="categoryData" :default-expanded-keys="expandedKey" show-checkbox
          node-key="id" :expand-on-click-node="false" :props="defaultProps" @check="handleCheckChange">
          <template #default="{ node, data }">
            <span class="custom-tree-node" style="font-size: 17px;">
              <span>{{ node.label }}</span>
              <span style="margin-left:20px;">
                <el-button type="primary" text size="small" :icon="Plus" @click="append(data)">添加</el-button>
                <el-button type="primary" text size="small" :icon="EditPen" @click="edit(data)">编辑</el-button>
                <el-button type="primary" text size="small" :icon="Delete" v-if="data.children.length === 0"
                  @click="remove(data)">删除</el-button>
              </span>
            </span>
          </template>
        </el-tree>
      </el-col>
    </el-row>
  </div>

  <!-- 添加对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="title" style="width: 35%;">
    <el-form :model="categoryForm" :rules="rules" status-icon style="width: 96%;" label-width="90px">
      <el-form-item label="分类名称" prop='name'>
        <el-input v-model="categoryForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="分类排序" prop='sort'>
        <el-input v-model="categoryForm.sort" autocomplete="off" />
      </el-form-item>
      <el-form-item label="是否展示">
        <el-switch v-model="categoryForm.visible" class="ml-2"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="0" :inactive-value="1" />
      </el-form-item>
      <el-form-item label="分类图标">
        <SingleUpload v-model:picture="categoryForm.icon" :uploadType="uploadType" :width="100" :height="100"
          ref="singleUploadComponent"></SingleUpload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="hadnlerCancel">取消</el-button>
        <el-button type="primary" @click="handlerConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang='scss'></style>